package kr.saeildamil.androidStudy_second.brservice;

import java.util.Calendar;

import kr.saeildamil.androidStudy_second.R;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Toast;

public class AlarmTest extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch29and30_alarmtest);
	}

	protected void onResume() {
		super.onResume();
		IntentFilter alarmFilter = new IntentFilter(
				"kr.saeildamil.androidStudy_second.ALARM");
		registerReceiver(AlarmReceiver, alarmFilter);

		IntentFilter scoreFilter = new IntentFilter(
				"kr.saeildamil.androidStudy_second.SCORE");
		registerReceiver(DisplayScore, scoreFilter);
	}

	protected void onPause() {
		super.onPause();
		unregisterReceiver(AlarmReceiver);
		unregisterReceiver(DisplayScore);
	}

	public void mOnClick(View v) {
		AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
		Intent intent;
		PendingIntent sender;

		switch (v.getId()) {
		case R.id.onetime:
			intent = new Intent("kr.saeildamil.androidStudy_second.ALARM");
			sender = PendingIntent.getBroadcast(this, 0, intent, 0);

			// 10초 후
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis()); // 시스템시간을 구함
			calendar.add(Calendar.SECOND, 5);// 현재시간 +10초

			// 알람등록
			am.set(AlarmManager.RTC, calendar.getTimeInMillis(), sender);
			break;
		case R.id.repeat:
			
		case R.id.stop:
			intent = new Intent("kr.saeildamil.androidStudy_second.SCORE");
			sender = PendingIntent.getBroadcast(this, 0, intent, 0);
			if(v.getId()==R.id.repeat){
				am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(), 5000, sender);
			} else {
				am.cancel(sender);
			}
			break;

		}
	}

	BroadcastReceiver AlarmReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "It's Time to Start", Toast.LENGTH_LONG)
					.show();
		}
	};

	BroadcastReceiver DisplayScore = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			Toast.makeText(context, "Kia : Samsung = 2:3", Toast.LENGTH_LONG)
					.show();
		}
	};
}
